#~/projects/voteForQiuGe.py
#coding=utf8

import httplib,urllib
import Queue
import threading
import time

class WorkManager(object):
	def __init__(self,work_num=100,thread_num=2):
		self.work_queue=Queue.Queue()
		self.threads=[]
		self.__init_work_queue(work_num)
		self.__init_thread_pool(thread_num)

	# init threads
	def __init_thread_pool(self,thread_num):
		for i in range(thread_num):
			self.threads.append(Work(self.work_queue))

	#init work queue
	def __init_work_queue(self,jobs_num):
		for i in range(jobs_num):
			self.add_job(do_job,i)

	#add job
	def add_job(self,func,*args):
		self.work_queue.put((func,list(args)))
	#check last queue
	def check_queue(self):
		return self.work_queue.qsize()
	#wait all thread
	def wait_allcomplete(self):
		for item in self.threads:
			if item.isAlive():
				item.join()

class Work(threading.Thread):
	def __init__(self,work_queue):
		threading.Thread.__init__(self)
		self.work_queue=work_queue
		self.start()
	def run(self):
		while True:
			try:
				do,args=self.work_queue.get(block=False)
				do(args)
				self.work_queue.task_done()
			except Exception,e:
				print "do work[%i] exception" % int(args[0])
				break

def do_job(args):
	httpClient=None
	print "start vote %i" % int(args[0])
	try:
		params= urllib.urlencode({"id":"33"})
		headers={
		"User-Agent":"Mozilla/5.0",
		"Content-Type":"application/x-www-form-urlencoded",
		"Accept":"application/json,text/javascript,*/*;q=0.01",
		"X-Requested-Width":"XMLHttpRequest"#,
		#"Accept-Encoding":"gzip,deflate"
		}

		httpClient=httplib.HTTPConnection("www.youxichaguan.com",80,30)
		httpClient.request("POST","/mgac2014/home.php/Talen/power.html",params,headers)
		response=httpClient.getresponse()


		content=response.read()
		if len(content)<50:
			print "status:"+str(response.status)
			print "reason:"+response.reason
			print "read:"+content
		#else:
		#	print "read:None"
		#print "hreaders:"+response.gethreaders()
	except Exception,e:
		print "vote[%i] exception:"+str(e) % int(args[0])
	finally:
		if httpClient:
			httpClient.close()

if __name__=='__main__':
	start=time.time()
	work_manager=WorkManager(500000,3)
	work_manager.wait_allcomplete()
	end=time.time()
	print "finish work,cost all time:%s" % (end-start)
